package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.hmdp.utils.RedisConstants.*;

/**
 * @author yu yang
 * @date 2022/10/12 -15:51
 */
@Component
public class CacheClient {
    private StringRedisTemplate stringRedisTemplate;
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);


    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //将任意Java对象序列化为json并存储在string类型的key中，并且可以设置TTL过期时间
    public void set(String key, Object value, Long time, TimeUnit timeUnit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, timeUnit);
    }

    //将任意Java对象序列化为json并存储在string类型的key中，并且可以设置逻辑过期时间，用于处理缓存击穿问题
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit timeUnit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(timeUnit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

//    根据指定的key查询缓存，并反序列化为指定类型，利用缓存空值的方式解决缓存穿透问题
    public <R,ID> R  queryWithPassThough(
            String prefix, ID id, Class<R> returnType, Function<ID,R> dbQuery,Long time,TimeUnit timeUnit) {
        String key = prefix + id;
        String jsonR = stringRedisTemplate.opsForValue().get(key);
        //缓存中的数据不为空直接返回
        if (StrUtil.isNotBlank(jsonR)) {
            return JSONUtil.toBean(jsonR, returnType);
        }
        //缓存中的数据为空值，为不存在的数据
        if ("".equals(jsonR)) {
            return null;
        }
        //从数据库获取
        R r = dbQuery.apply(id);
        //数据库和缓存都不存在
        if (r == null) {
            //向缓存中存储空对象
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        this.set(key,r,time,timeUnit);
        return r;

    }

    //根据指定的key查询缓存，并反序列化为指定类型，需要利用逻辑过期解决缓存击穿问题将逻辑进行封装
    public <R,ID> R queryWithLogicExpire(
            String prefix, ID id, Class<R> returnType, Function<ID,R> dbQuery,Long time,TimeUnit timeUnit) {
        String key = prefix + id;
        //1.从缓存中获取数据
        String json = stringRedisTemplate.opsForValue().get(key);
        //2.热点数据会提前缓存预热，没有命中缓存直接返回
        if (StrUtil.isBlank(json)){
            return null;
        }
        //命中后反序列化对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), returnType);
        LocalDateTime expireTime = redisData.getExpireTime();
        //3.判断缓存是否过期
        //4.未过期直接返回
        if (LocalDateTime.now().isBefore(expireTime)){
            return r;
        }
        //5.过期进行缓存重构
        // 获得互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = this.tryLock(lockKey);
        if (isLock){
            if (LocalDateTime.now().isAfter(expireTime)){
                CACHE_REBUILD_EXECUTOR.submit( ()->{
                    try{
                        R newR = dbQuery.apply(id);
                        //重建缓存
                        this.setWithLogicalExpire(key,newR,time,timeUnit);
                    }catch (Exception e){
                        throw new RuntimeException(e);
                    }finally {
                        unlock(lockKey);
                    }
                });
            }
        }
        //6.返回过期数据
        return r;
    }
    //根据指定的key查询缓存，并反序列化为指定类型，需要利用互斥锁解决缓存击穿问题将逻辑进行封装
    public <R,ID> R queryWithMutex(
            String prefix, ID id, Class<R> returnType, Function<ID,R> dbQuery,Long time,TimeUnit timeUnit){
        String key = prefix + id;
        String Json = stringRedisTemplate.opsForValue().get(key);

        if (StrUtil.isNotBlank(Json)){
            return JSONUtil.toBean(Json, returnType);
        }
        if ("".equals(Json)){
            return null;
        }

        String lockKey = LOCK_SHOP_KEY + id;
        //尝试获取锁
        boolean islock = this.tryLock(lockKey);
        R r = null;
        try {
            if (!islock) {
                //获取失败，从缓存命中重新开始
                Thread.sleep(50);
                return queryWithMutex(prefix,id,returnType,dbQuery,time,timeUnit);
            }
            r = dbQuery.apply(id);
            if (r == null) {
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            this.set(key,r,time,timeUnit);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            this.unlock(lockKey);
        }
        return r;
    }


    private boolean tryLock(String lockKey) {
        //从缓存中设置key，如果key已经存在，返回false，意味着没有获得锁
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    private void unlock(String lockKey) {
        stringRedisTemplate.delete(lockKey);
    }


}
